package com.wantup.remote.server;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/** 服务端，使用多线程一直开着Socket监听客户端连接
 * @author wangshangyi
 * @version V1.0  2020/8/14 11:17
 */
public class Server {
    private final static int PORT = 12000;

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(PORT);
            while (true) {
               new ShotThread(server).start();
            }
        } catch (IOException ee) {
            ee.printStackTrace();
        }
    }
}

/**
 * 线程类，负责获取截图，并发送给客户端
 */
class ShotThread extends Thread {
    Socket connection;

    ShotThread(ServerSocket server) throws IOException {
        this.connection = server.accept();
    }

    public void run() {
        System.out.println("得到连接:");
        java.awt.image.BufferedImage image = (new ShotImage()).snapShot();
        String imageFormat = "jpg";
        if (image != null) {
            try {
                javax.imageio.ImageIO.write(image, imageFormat, connection
                        .getOutputStream());
                System.out.println("sendSuccess");
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * 获取截屏图片
 */
class ShotImage {
    private BufferedImage screenShot;
    private Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();

    synchronized BufferedImage snapShot() {
        try {
            screenShot = (new Robot()).createScreenCapture(new Rectangle(0, 0,
                    (int) dimension.getWidth(), (int) dimension.getHeight()));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return screenShot;
    }
}
